package com.easy.common.util.auth;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DigestUtility {
	private static final char HEX_ARRAY[] = {
		'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
		'a', 'b', 'c', 'd', 'e', 'f'
	};
	private static MessageDigest md = null;

	public DigestUtility()
	{
	}

	public static synchronized byte[] md5(byte inputData[])
	{
		if (md == null)
		{
			return null;
		} else
		{
			md.reset();
			md.update(inputData);
			return md.digest();
		}
	}

	public static synchronized String md5Hex(byte srcBytes[])
	{
		byte md5Array[] = md5(srcBytes);
		StringBuffer rtStr = new StringBuffer();
		for (int i = 0; i < md5Array.length; i++)
		{
			byte high = (byte)(md5Array[i] >> 4 & 0xf);
			byte low = (byte)(md5Array[i] & 0xf);
			rtStr.append(HEX_ARRAY[high]);
			rtStr.append(HEX_ARRAY[low]);
		}

		return rtStr.toString();
	}

	public static synchronized boolean isMatch(byte currData[], String digest)
	{
		if (currData == null || digest == null)
		{
			return false;
		} else
		{
			String realDigest = md5Hex(currData);
			return digest.equals(realDigest);
		}
	}

	public static synchronized String md5File(String filePath)
	{
		InputStream in;
		if (md == null)
			return null;
		md.reset();
		in = null;
		File file = new File(filePath);
		if (!file.exists() || !file.isFile())
		{
			return null;
		}
		try
		{
			in = new BufferedInputStream(new FileInputStream(file));
			byte buf[] = new byte[10240];
			for (int readLen = 0; (readLen = in.read(buf)) > 0;)
				md.update(buf, 0, readLen);

		}
		catch (Exception ex)
		{
			try
			{
				if (in != null)
					in.close();
			}
			catch (Exception exception2) { }
			return null;
		}
		byte md5Array[] = md.digest();
		StringBuffer rtStr = new StringBuffer();
		for (int i = 0; i < md5Array.length; i++)
		{
			byte high = (byte)(md5Array[i] >> 4 & 0xf);
			byte low = (byte)(md5Array[i] & 0xf);
			rtStr.append(HEX_ARRAY[high]);
			rtStr.append(HEX_ARRAY[low]);
		}

		return rtStr.toString();
	}

	public static synchronized boolean isFileMatch(String filePath, String digest)
	{
		if (digest == null)
		{
			return false;
		} else
		{
			String realDigest = md5File(filePath);
			return digest.equals(realDigest);
		}
	}

	static 
	{
		try
		{
			md = MessageDigest.getInstance("MD5");
		}
		catch (NoSuchAlgorithmException nosuchalgorithmexception) { }
	}

}
